<template>
  <div class="loginpage">
    <div class="video">
      <video src="./../../img/background.mp4" autoplay loop muted></video>
    </div>
    <div class="left"></div>
    <div class="right">
      <div class="text">千锋管理系统</div>
      <el-form
        :model="Loginfrom"
        status-icon
        :rules="rules"
        ref="Loginfrom"
        label-width="100px"
        class="demo-Loginfrom"
      >
        <el-form-item label="用户名" prop="username">
          <!-- 其中prop=username是对下方return里的rules里的username进行校验 -->
          <el-input
            type="text"
            v-model="Loginfrom.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passworld">
          <el-input
            type="password"
            v-model="Loginfrom.passworld"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('Loginfrom')"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
//登录逻辑的实现
//1.收集用户输入的username&password传递给后端
//2.登录通过后，将后台返回的token存到本地，并跳转到主页
//3.每次请求的时候携带token到请求头，传的字段是authorization
//4.展示token效验正确的数据
//5.校验不通过跳转到登录页·
import { login } from "@/api";
import {mapMutations} from "vuex"
export default {
  data() {
    //返回了数据username和passworld
    /**
     * @param {Object} rule 就是一个表单验证对象  @param 为要描述的函数的参数 Object为类型，rule为描述的字段
     * @param {String} value 输入值
     * @param {Function} callback 校验通过不传参，校验不通过传参
     */
    var validateusername = (rule, value, callback) => {
      //其中value为输入框中的值
      /* if (value === "") {
        callback(new Error("请输入用户名"));
      } else {
        if (this.Loginfrom.passworld !== "") {
          this.$refs.Loginfrom.validateField("passworld");
        }
        callback(); //没有参数时代表校验通过
      } */
      if (!value) {
        callback("4到16位（字母，数字，下划线，减号）");
      } else {
        callback();
      }
    };
    var validatepassworld = (rule, value, callback) => {
      if (!value) {
        callback("请输入密码");
      } else {
        callback();
      }
    };
    return {
      Loginfrom: {
        username: "",
        passworld: "",
      },
      rules: {
        username: [{ validator: validateusername, trigger: "blur" }], //trigger触发，blur失去焦点
        passworld: [{ validator: validatepassworld, trigger: "blur" }],
      },
    };
  },
  methods: {
    ...mapMutations(['SET_USERINFO']),
    submitForm(formName) {
      "";
      this.$refs[formName].validate((valid) => {
        //本地校验通过
        if (valid) {
          //本地校验通过后,打开登录加载动画
          const loading = this.$loading({
            lock: true,
            text: "正在登录...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          //发送请求`
          login(this.Loginfrom.username, this.Loginfrom.passworld)
            .then((res) => {
              //登录成功后，关闭加载动画
              loading.close();
              if (res.data.state) {
                //console.log(res);
                 this.$message.success("登陆成功")
                localStorage.setItem("login-tokin", res.data.token);
                localStorage.setItem("login-userInfo",JSON.stringify(res.data.userInfo))

                //更改vuex中state['userInfo']的值
                  this.SET_USERINFO(res.data.userInfo)
                //登陆成功跳转到主页
                this.$router.push("/welcome");
              } else {
                this.$message.error("用户名或密码错误")
              }
            })
            .catch((err) => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style scoped>
/* 样式局部化 */
/* 表单样式 */
.right {
  background: rgba(0, 0, 0, 0.3);
  width: 400px;
  height: 80%;
  position: absolute;
  right: 5%;
  top: 10%;
}
.el-form {
  width: 400px;
}
.text {
  color: white;
  width: 100%;
  text-align: center;
  font-size: 30px;
  margin-top: 30%;
  margin-bottom: 10%;
}

.loginpage .video {
  position: absolute;
  top: 0;
  left: 0;
  z-index: -100;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.left {
  width: 50%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: url("./../../img/bg2.png") no-repeat;
  background-size: 50%;
  background-position-x: 60%;
  background-position-y: 65%;
  opacity: 0.7;
}
.el-button {
  display: inline-block;
  text-align: center;
  width: 83%;
  background: linear-gradient(90deg, #1596fb, #002dff);
}
</style>